import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, ScrollView, Text, Image } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { isTimeIntervalValid } from '../../utils/pagination'
import Constants from '../../config/constants'
import CollectionService from '../../services/collect'
import { Utils } from '../../utils/utils'
import { getNextPage } from '../../utils/pagination'

import ProductList from '../../components/product-list'
import TextHeader from '../../components/text-header'

import './index.scss'


// #region 书写注意
// 
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

const collectionService = new CollectionService()
const utils = new Utils()

type PageStateProps = {
  collectionList: any[],
  activeTabIndex: number,
  effects: any,
  collectionLastLoadTime: number,
  userApplyList: any[],
  collectionNoneResult: boolean,
  collectionNoneResultTips: string,
  collectionPage: number,   // 当前收藏列表页
  defaultPageSize: number,  // 每页条数
}

type PageDispatchProps = {
  getMyCollection: (param: any) => void,
  dispatchRefresh: () => void,
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface MyCollection {
  props: IProps;
  state: PageState;
}

@connect(({ myCollection, common, loading }) => ({
  ...myCollection,
  ...common,
  ...loading,
}), (dispatch) => ({
  getMyCollection(param: any) {
    dispatch({
      type: 'myCollection/getMyCollection',
      payload: param,
    })
  },
  dispatchRefresh() {
    dispatch({
      type: 'myCollection/refreshMyCollection',
    })
  }
}))
class MyCollection extends Component {

  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(nextProps) {

  }

  componentWillMount() {
    // 加载数据
    this.reloadCollection()
  }

  componentDidMount() {
    // 监听取消收藏
    this.initCancelCollectWatch()
  }

  componentWillUnmount() {
    // 取消监听
    this.removeCancelCollectWatch()
  }

  componentDidShow() {
  }

  componentDidHide() { }

  render() {
    const { collectionList, userApplyList, collectionNoneResult, collectionNoneResultTips } = this.props
    // console.log('state.searchOption = ', this.state.searchOption)
    // console.log('searchOption = ', searchOption)

    return (
      <View className='my-collection-container'>

        <View className="header">
          <TextHeader title={'我的收藏'} />
        </View>

        <ScrollView
          scrollY
          scrollWithAnimation
          scrollTop={0}
          lowerThreshold={0}
          style='height: 93vh'
          onScrollToLower={this.onLoadMoreCollection.bind(this)}>

          <ProductList
            dataArray={collectionList}
            userApplyList={userApplyList}
            isShowCheck={false} isShowLoanTime={true} isShowApply={true} isShowCollectCancel={true}
            loading={this.props.effects['myCollection/getMyCollection']}
            noneResult={collectionNoneResult}
            noneResultTips={collectionNoneResultTips} />

        </ScrollView>
      </View>
    )
  }

  /**
   * 滚动到底部触发，加载更多
   * @param e 
   */
  onLoadMoreCollection(e) {
    if (this.props.effects['myCollection/getMyCollection']) {
      // console.log('加载数据中，return !!!', e)
      return
    }
    if (!isTimeIntervalValid(this.props.collectionLastLoadTime)) {
      // console.log('太频繁了，return !!!', e)
      return
    }
    this._loadMoreCollection()
  }

  /**
   * 加载更多收藏
   */
  _loadMoreCollection() {
    this.props.getMyCollection({
      page: getNextPage(this.props.collectionPage, this.props.defaultPageSize, this.props.collectionList.length)
    })
  }

  /**
   * 重新加载收藏产品列表
   */
  reloadCollection() {
    this.props.dispatchRefresh()
  }

  /**
   * 取消收藏监听
   */
  initCancelCollectWatch() {
    const that = this
    Taro.eventCenter.on(Constants.PRODUCT_CANCLE_COLLECT_EVENT, (param) => {
      const { collection_id } = param
      if (collection_id) {

        Taro.showModal({
          title: '取消收藏',
          content: '确定要取消收藏该产品?',
          success(res) {
            if (res.confirm) {

              utils.showLoadingCenter()

              collectionService.removeCollection([collection_id]).then(res => {
                utils.hideLoadingCenter()
                // console.log('用户点击确定, product = ', product)
              }, error => {
                utils.hideLoadingCenter()
              }).then(res => {
                // 取消收藏后重新加载
                that.reloadCollection()
              })

            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          }
        })
      }
    })
  }

  /**
   * 取消监听
   */
  removeCancelCollectWatch() {
    Taro.eventCenter.off(Constants.PRODUCT_CANCLE_COLLECT_EVENT)
  }

}
// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default MyCollection as ComponentClass<PageOwnProps, PageState>
